import Config from './config.js'

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: Config.common_text.date_UNITS,
	humanize: function(date){
		var date = dateUtils.parse(date);
		var millSec = new Date().getTime() - date.getTime();
		var time = this.humanize2(millSec);
		return time;
	},
	humanize2: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + Config.common_text.pre_time;
				break;
			}
		}
		return humanize || Config.common_text.now_time;
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < 86400000) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},
	
	expire_val: function(dateStr1, dateStr2){
		var stamp1 = new Date(dateStr1).getTime();
		var stamp2 = new Date(dateStr2).getTime();
		var millis = Math.abs(stamp1-stamp2);
		var day = Math.ceil(millis/1000/86400);
		if(day >=1 ){
			return day;
		}
		var inFifteenMinutes = new Date(new Date().getTime() + millis);
		return inFifteenMinutes;
	}
};
var mapUtils = {
	openMap: function(title, lat, lon){
		var url = "";
		var src = "com.gg.cut";
		var dev = "0";
		if (plus.os.name=="Android") {  
			var hasBaiduMap = plus.runtime.isApplicationExist({pname:'com.baidu.BaiduMap',action:'baidumap://'});  
			var hasAmap = plus.runtime.isApplicationExist({pname:'com.autonavi.minimap',action:'androidamap://'});  
			var urlBaiduMap = "baidumap://map/marker?location="+lat+","+lon+"&title="+title+"&src="+src;  
			var urlAmap = "androidamap://viewMap?sourceApplication="+src+"&poiname="+title+"&lat="+lat+"&lon="+lon+"&dev="+dev;  
			console.log('hasAmap && hasBaiduMap ', hasAmap && hasBaiduMap)
			if (hasAmap && hasBaiduMap ) {
				plus.nativeUI.actionSheet({title:"选择地图应用",cancel:"取消",buttons:[{title:"百度地图"},{title:"高德地图"}]}, function(e){  
					switch (e.index){  
						case 1:  
							plus.runtime.openURL(encodeURI(urlBaiduMap));  
							break;  
						case 2:  
							plus.runtime.openURL(encodeURI(urlAmap));  
							break;  
					}  
				})  
			}  
			else if (hasAmap) {  
				plus.runtime.openURL(encodeURI(urlAmap));  
			}  
			else if (hasBaiduMap) {  
				plus.runtime.openURL(encodeURI(urlBaiduMap));  
			}  
			else{  
				url = "geo:"+lat+","+lon+"?q="+title;  
				plus.runtime.openURL(encodeURI(url)); //如果是国外应用，应该优先使用这个，会启动google地图。这个接口不能统一坐标系，进入百度地图时会有偏差  
				plus.runtime.openURL( encodeURI(url), function( e ) {
					console.log('not found', e)
					uni.openLocation({
						latitude: parseFloat(lat),
						longitude: parseFloat(lon),
						success: function () {
							console.log('openLocation success');
						}
					});
				});  
			}  
		} else{  
			// iOS上获取本机是否安装了百度高德地图，需要在manifest里配置，在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加（如urlschemewhitelist:["iosamap","baidumap"]）  
			plus.nativeUI.actionSheet({title:"选择地图应用",cancel:"取消",buttons:[{title:"Apple地图"},{title:"百度地图"},{title:"高德地图"}]}, function(e){  
				console.log("e.index: " + e.index);  
				switch (e.index){  
					case 1:  
						url = "http://maps.apple.com/?q="+title+"&ll="+lat+","+lon+"&spn=0.008766,0.019441";  
						break;  
					case 2:  
						url = "baidumap://map/marker?location="+lat+","+lon+"&title="+title+"&src="+src;  
						break;  
					case 3:  
						url = "iosamap://viewMap?sourceApplication="+src+"&poiname="+title+"&lat="+lat+"&lon="+lon+"&dev="+dev;  
						break;  
					default:  
						break;  
				}  
				if (url!="") {  
					plus.runtime.openURL( encodeURI(url), function( e ) {  
						plus.nativeUI.alert("本机未安装指定的地图应用");  
					});  
				}  
			})  
		}  
	}

}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	mapUtils: mapUtils
}
